// Helper.cpp: implementation of the CHelper class.
//
//////////////////////////////////////////////////////////////////////

#include "Helper.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CHelper::CHelper(int nOptions)
{
	int i;
	m_nOptions=nOptions;
	
	//Initialize help area
	m_straHelp=new char* [m_nOptions];
	for(i=0;i<m_nOptions;i++)
		m_straHelp[i]=NULL;

	//Initialize intro message
	m_strProgramName=NULL;
	m_strHeadMessage=NULL;
	m_strUsageLine=NULL;
	m_strTailMessage=NULL;
}

CHelper::~CHelper()
{
	int i;

	for(i=0;i<m_nOptions;i++)
		if(m_straHelp[i]) delete[] m_straHelp[i];
	
	if(m_straHelp) 
		delete[] m_straHelp;
	
	if(m_strProgramName) 
		delete[] m_strProgramName;
	if(m_strHeadMessage) 
		delete[] m_strHeadMessage;
	if(m_strUsageLine) 
		delete[] m_strUsageLine;
	if(m_strTailMessage) 
		delete[] m_strTailMessage;

}

void CHelper::fillProgramName(char *strMessage)
{
	deleteAndCopy(&m_strProgramName,strMessage);
}

void CHelper::fillHeadMessage(char *strMessage)
{
	deleteAndCopy(&m_strHeadMessage,strMessage);
}

void CHelper::fillUsageLine(char *strMessage)
{
	deleteAndCopy(&m_strUsageLine,strMessage);

}

void CHelper::fillTailMessage(char *strMessage)
{
	deleteAndCopy(&m_strTailMessage,strMessage);
}

void CHelper::fillHelpForOption(int nPos, char cOption, char* strValue)
{
	if(nPos>=m_nOptions)
		return;	//throw exception

	if(m_straHelp[nPos]) delete[] m_straHelp[nPos];
	m_straHelp[nPos]=new char[1+strlen(strValue)+1];
	m_straHelp[nPos][0]=cOption;
	strcpy(m_straHelp[nPos]+1,strValue);

}

void CHelper::displayHelp()
{
	if(m_strProgramName)	
		std::cout<<m_strProgramName<<std::endl;
	if(m_strHeadMessage)	
		std::cout<<m_strHeadMessage<<std::endl;
	if(m_strUsageLine)		
		std::cout<<std::endl<<"Usage: "<<m_strUsageLine<<std::endl;
	
	std::cout<<std::endl<<"OPTIONS"<<std::endl;
	for(int i=0;i<m_nOptions;i++){
		if(m_straHelp[i])
			std::cout<<m_straHelp[i][0]<<"\t- "<<m_straHelp[i]+1<<std::endl;
	}

	if(m_strTailMessage)	
		std::cout<<std::endl<<m_strTailMessage<<std::endl;
}


char** CHelper::getBuffer()
{
	return m_straHelp;
}

void CHelper::deleteAndCopy(char **dest, char *source)
{
	if(*dest) delete[] *dest;
	*dest=new char[strlen(source)+1];
	strcpy(*dest,source);
}
